<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/31
 * Time: 16:00
 */

namespace app\api\controller\android\v1;


use think\Cache;
use think\Controller;
use app\api\model\Authority;
use think\db;
use think\Request;

class User extends Controller
{
    protected $model;
    protected $us;

    public function _initialize()
    {
        $this->model = new Authority();
        $this->us    = $this->model->check(1);
    }

    /**
     * 修改手机号
     */
    public function reset_mobile()
    {
        $data = $this->model->post(['code', 'new_mobile']);
        if (!is_mobile($data['new_mobile'])) {
            r_date([], 300, '请输入正确的手机号');
        }
        $s_verify = Cache::get(md5($data['new_mobile']));
        if (empty($data['code']) || $data['code'] != $s_verify) {
            r_date([], 300, '验证码错误');
        }
        Cache::clear(md5($data['new_mobile']));
        $user = self::$user;
        if (db('user')->where(['mobile' => $data['new_mobile'], 'status' => ['in', '0,1,2']])->find()) {
            r_date([], 300, '该手机号已注册用户端，请重新选择手机号');
        }
        $res = db('user')->where(['user_id' => $user['user_id']])->update(['mobile' => $data['new_mobile']]);
        if ($res !== false) {
            r_date();
        }
        r_date([], 300, '修改失败，请刷新后重试');
    }

    public function index()
    {

        $retrun    = db('user')->field('user.user_id,user.mobile,user.username,user.avatar,user.sex,user.state,st.store_name,user.number')->join('store st', 'st.store_id=user.store_id', 'left')->where(['user_id' => $this->us['user_id']])->find();
        $BeginDate = date('Y-m-01', strtotime(date("Y-m-d", time())));
        $starttime = strtotime($BeginDate);
        $enttime   = strtotime(date('Y-m-d', strtotime("$BeginDate +1 month -1 day")));
        $quantity  = db('order')->where(['created_time' => ['between', [$starttime, $enttime]], 'assignor' => $this->us['user_id']])->count();//本月接单量
        $volume    = $this->shang( $this->us['user_id']);
        $message   = db('message')->where(['already'=>1,'user_id'=>$this->us['user_id']])->field('content,id,type,order_id')->orderRaw('already=1 desc,time desc')->select();

        if($message){
           foreach ($message as $key => $val) {
               $content[$key]['content']= $val["content"];
               $content[$key]['id']= $val["id"];
               $content[$key]['order_id']= $val["order_id"];
               $content[$key]['type']= $val["type"];
           }
           $retrun['message']= $content;
       }else{
           $retrun['message'] = null;
       }

        $retrun['quantity'] = $quantity;
        $retrun['signing']  = $volume['signing'];
        $retrun['volume']   = $volume['volume'];


        $retrun['message_count']  = count($message);
        r_date($retrun, 200, '获取成功');
    }

    /**
     * 修改我的状态
     */
    public function state()
    {
        $data = $this->model->post(['state']);
        //店长在线时长统计
        db('online')->insertGetId(['user_id' => $this->us['user_id'],'startTime'=>time(),'type'=>$data['state'],'time'=>time()]);

        $res  = db('user')->where(['user_id' => $this->us['user_id']])->update(['state' => $data['state']]);

        if ($res) {
            r_date([], 200);
        }
        r_date([], 300, '状态修改失败，请刷新后重试');
    }

    /**
     * 修改资料
     * invoice_type
     */
    public function edit()
    {
        $data = $this->model->post(['avatar']);
        $res  = db('user')->where(['user_id' => $this->us['user_id']])->update([
            'avatar' => $data['avatar']
        ]);
        if ($res !== false) {
            r_date([], 200);
        }
        r_date([], 300, '编辑失败，请刷新后重试');
    }

    /*
     * 上门成交率/本月签约
     */
    private function shang($user_id)
    {
        $BeginDate = date('Y-m-01', strtotime(date("Y-m-d", time())));
        $starttime = strtotime($BeginDate);
        $enttime   = strtotime(date('Y-m-d', strtotime("$BeginDate +1 month -1 day")));
        //成交个订单再今天签约的
        $g1 = db('contract')->where(['con_time' => ['between', [$starttime, $enttime]],'type'=>1])->field('orders_id')->select();

        $s1 = '';
        foreach ($g1 as $key => $val) {
            $s1 .= $val["orders_id"] . ',';
        }
        $s1 = substr($s1, 0, -1);
        //当月成交个数
        $deal = db('order')->where(['order_id' => ['in', $s1], 'assignor' => $user_id,'state'=>['<',8]])->field('order_id,ification')->select();
        $p=0;
        foreach ($deal as $key => $val) {
            if ($val['ification'] == 2) {
                $cap      = db('capital')->where(['ordesr_id' => $val['order_id'], 'types' => 1, 'enable' => 1])->sum('to_price');
                $ca       = db('envelopes')->where(['ordesr_id' => $val['order_id']])->field('give_money')->find();
                $p+= $cap - $ca['give_money'];
            }
            if ($val['ification'] == 1){
                $ca       = db('capital')->where(['ordesr_id' => $val['order_id'], 'types' => 1, 'enable' => 1])->field('sum(to_price),sum(give_money)')->find();
                $p+= $ca['sum(to_price)'] - $ca['sum(give_money)'];
            }
        }

        // 当月上门个数
        $dea=count($deal);
        $shang_count = db('order')->where(['assignor' => $user_id, 'planned' =>['between', [$starttime, $enttime]]])->count();//上门量订单包括取消的
        if (!empty($dea) && !empty($shang_count)) {
            $turnovers = ($dea / $shang_count) * 100;//上门成交率
        } else {
            $turnovers = 0;
        }

        $data = [
            'volume' => $turnovers,
            'signing' => $p,
        ];
        return $data;
    }

    public function Article()
    {
        $result  = send_post(U_SRC . "/support/v1.article/all",[]);


       return r_date(json_decode($result,true),200);
    }
    public function Article_list()
    {
        $data=$this->model->post(['category_id','limit','page']);
        $result  = send_post(U_SRC . "/support/v1.article/lists",$data);

        return r_date( json_decode($result,true),200);
    }

    /*
     * 免打扰
     */
    public function disturb()
    {
        $this->model->post(['type']);
        db('user')->where('user_id',$this->us['user_id'])->update(['disturb'=>2]);
        r_date([], 200);
    }
    /*
     * 获取地理位置
     */
    public function lat(){
        $data=$this->model->post(['lat','lng']);
        db('user')->where('user_id', $this->us['user_id'])->update(['lat' => $data['lat'], 'lng' => $data['lng']]);
        r_date(null, 200);
    }
    /*
     * 免打扰
     */
    public function about()
    {
        $da=db('about')->find();
        r_date($da, 200);
    }

    /*
     * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
     */
    public function message()
    {

        $message = db('message')->field('type,content,order_id,already,id')->where(['user_id' => $this->us['user_id']])->limit(0, 3)->orderRaw('already=1 desc,time desc')->select();
        $data    = [
            'data' => $message,
            'count1' => db('message')->where(['user_id' => $this->us['user_id'], 'type' => ['in','2,3,4,6'], 'already' => 1])->count(),
            'count2' => db('message')->where(['type' => 5, 'already' => 1,'user_id' => $this->us['user_id']])->count(),
            'count3' => db('message')->where([ 'type' => 1, 'already' => 1,'user_id' => $this->us['user_id']])->count(),
            'count4' => 0,
            'count5' => db('message')->where(['user_id' => $this->us['user_id'], 'already' => 1])->count(),
        ];
        r_date($data, 200);
    }

    /*
    * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
    */
    public function message_list()
    {
        //0全部1系统2订单5公司通知7未读
        $data = $this->model->post(['type', 'page' => 1, 'limit' => 10, 'title']);
        $me   = db('message');
        if (isset($data['title']) && $data['title'] != '') {
            $map['content'] = array('like', "%{$data['title']}%");
            $me->where($map);
        }
        if($data['type']==2){
            $me->where(['type'=>['in','3,4,6']]);
        }elseif ($data['type']==7){
            $me->where(['already'=>1]);
        }elseif($data['type']==5){
            $me->where(['type'=>$data['type']]);
        }elseif($data['type']==1){
            $me->where(['type'=>$data['type']]);
        }
        $message = $me->where(['user_id'=>$this->us['user_id']])->field('id,type,content,order_id,already')
            ->orderRaw('already=1 desc,time desc')
            ->page($data['page'], $data['limit'])
            ->select();
        r_date($message, 200);
    }

    /*
    * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
    */
    public function message_info()
    {
        $data            = $this->model->post(['id']);
        $message         = db('message')->where('id', $data['id'])->field('type,content,order_id,already,time')->find();
        $message['time'] = date('Y-m-d H:i:s');
        if($message['already'] !=0){
            db('message')->where('id', $data['id'])->update(['already'=>0,'have'=>time()]);
        }

        r_date($message, 200);
    }

    /**
     * 获取后台客户注册的
     */
    public function jp(){
        $message         = db('admin')->field('username,logo,admin_id')->where(['status'=>0,'jp'=>1])->select();
        r_date($message, 200);
    }

//    public function get_order()
//    {
//
//        $start_time = strtotime(date("Y-m-d", time()));
//        //当天结束之间
//        $end_time = $start_time + 60 * 60 * 24;
//        $data     = $this->model->post(['state', 'page' => 1, 'limit' => 10]);
//        $m        = db('order')
//            ->alias('a')
//            ->field('a.order_id,a.ification,a.order_no,a.addres,a.contacts,a.telephone,a.remarks,a.created_time,a.state,a.quotation,a.planned,b.title,p.province,c.city,u.county,go.title')->join('chanel b', 'a.channel_id=b.id', 'left')
//            ->join('province p', 'a.province_id=p.province_id', 'left')
//            ->join('city c', 'a.city_id=c.city_id', 'left')
//            ->join('county u', 'a.county_id=u.county_id', 'left')
//            ->join('goods_category go', 'a.pro_id=go.id', 'left')
//            ->where(['a.assignor' => $this->us['user_id']]);
//
//
//        if ($data['state'] == 1) {
//            $m->where(['a.state' => 1])->order('a.planned desc');
//        } elseif ($data['state'] == 2) {
//            $m->where(['a.state' => 2])->order('a.update_time desc');
//        } elseif ($data['state'] == 3) {
//            $m->where(['a.through_id' => ['NEQ', 'NULL']])->order('a.order_id desc');
//        }
//
//        $list = $m->page($data['page'], $data['limit'])->select();
//        foreach ($list as $k => $key) {
//            $list[$k]['created_time'] = !empty($key['created_time']) ? date('Y-m-d H:i:s', $key['created_time']) : '';
//            $list[$k]['planned']      = !empty($key['planned']) ? date('Y-m-d H:i:s', $key['planned']) : '';
//            if ($data['state'] == 2) {
//
//            }
//            if ($data['state'] == 1) {
//
//            }
//
//            if ($data['state'] == 3) {
//                $thro = db('through')->where(['order_ids' => $key['order_id'], 'end_time' => ['between', [$start_time, $end_time]]])->order('th_time desc')->select();
//                if ($thro) {
//                    $list[$k]['msg'] = "今日需要跟进";
//                } else {
//                    $list[$k]['msg'] = null;
//                }
//
//            } else {
//                $list[$k]['msg'] = null;
//            }
//
//
//            $list[$k]['end_time'] = !empty($i['end_time']) ? date('Y-m-d H:i:s', $i['end_time']) : '';
//            if ($i) {
//                if ($data['orderType'] != 1) {
//                    unset($list[$k]);
//                }
//
//            } else {
//                $list[$k]['end_time'] = '';
//            }
//        }
//
//        r_date(array_merge($list));
//    }



}